package com.yogee.topseller.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.adapter.ExpressCompanyAdapter;
import com.yogee.topseller.bean.RetunContactBean;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.view.ClearEditText;
import com.yogee.topseller.zxing.MipcaActivityCapture;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 回寄合同详情
 *
 * @author hanyu
 *         created by 2017/7/12 10:09
 */
public class ReturnContractActivity extends HttpActivity implements ExpressCompanyAdapter.OnClickListener {

    @BindView(R.id.title_white_left_back)
    LinearLayout titleWhiteLeftBack;
    @BindView(R.id.title_white_title)
    TextView titleWhiteTitle;
    @BindView(R.id.iv_show_list)
    LinearLayout ivShowList;
    @BindView(R.id.lv_express_list)
    RecyclerView lvExpressList;
    @BindView(R.id.gongsi_tv)
    TextView gongsiTv;
    @BindView(R.id.cet_code_input)
    ClearEditText cetCodeInput;
    @BindView(R.id.tv_return_address)
    TextView tvReturnAddress;
    @BindView(R.id.tv_return_phone)
    TextView tvReturnPhone;

    private boolean isShow = false;
    private String orderId;//订单id
    private List<RetunContactBean.DisLists> beans;//快递列表
    private ExpressCompanyAdapter mAdapter;
    private String disCom = "", disNum = "";//快递公司id，填写的快递单号
    private static String[] PERMISSIONS_CARAMS = {Manifest.permission.CAMERA};//权限
    private final int PHOTO_CARMERACODE = 0x101;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_return_contract;
    }

    @Override
    protected void initView() {
        beans = new ArrayList<>();
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra("proId");
        }
        titleWhiteTitle.setText("合同回寄");
        lvExpressList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ExpressCompanyAdapter(this, this);
        lvExpressList.setAdapter(mAdapter);
        loadExpressList(orderId);
        cetCodeInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                loadConfirm(cetCodeInput.getText().toString());
            }
        });
    }
    
    /**
     * 获取快递列表
     */
    private void loadExpressList(String orderId) {
        HttpManager.getInstance().getDisList(orderId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<RetunContactBean>() {
            @Override
            public void onNext(RetunContactBean o) {
                if ("1".equals(o.getResult())) {
                    beans.clear();
                    tvReturnAddress.setText(o.getAddress());
                    tvReturnPhone.setText(o.getPhone());
                    beans.addAll(o.getDisList());
                    mAdapter.addData(beans);
                }
            }
        }, this));
    }

    @OnClick({R.id.iv_show_list, R.id.title_white_left_back, R.id.iv_qr_code, R.id.tv_return_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_white_left_back:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                finish();
                break;
            case R.id.iv_show_list:
                if (isShow) {
                    lvExpressList.setVisibility(View.GONE);
                } else {
                    lvExpressList.setVisibility(View.VISIBLE);
                }
                isShow = !isShow;
                break;
            case R.id.iv_qr_code:
                if (Build.VERSION.SDK_INT >= 23) {
                    requestPermissions(PERMISSIONS_CARAMS, PHOTO_CARMERACODE);
                } else {
                    if (cameraIsCanUse()) {
                        Intent intent = new Intent();
                        intent.setClass(ReturnContractActivity.this, MipcaActivityCapture.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivityForResult(intent, Config.SCANNIN_GREQUEST_CODE);
                    } else {
                        ToastUtils.showToast(ReturnContractActivity.this, "请到设置里设置拍照等权限");
                    }
                }
                break;
            case R.id.tv_return_confirm:
                confirmReturn();
                break;
        }

    }


    /**
     * 返回true 表示可以使用  返回false表示不可以使用
     */
    public boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }
        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    /**
     * 根据扫描或者输入的订单号，获取快递
     *
     * @param code
     */
    private void loadConfirm(String code) {
        HttpManager.getInstance().getDisNmae(code).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<RetunContactBean>() {
            @Override
            public void onNext(RetunContactBean o) {
                if ("1".equals(o.getResult())) {
                    beans.clear();
                    beans.addAll(o.getDisList());
                    mAdapter.addData(beans);

                    for (RetunContactBean.DisLists lists : beans) {
                        if (lists.getIsSelected().equals("1")) {
                            gongsiTv.setText(lists.getDisName());
                            break;
                        }
                    }
                }
            }
        }, this));
    }

    /**
     * 确认回寄合同
     */
    private void confirmReturn() {
        if (TextUtils.isEmpty(cetCodeInput.getText().toString())) {
            ToastUtils.showToast(ReturnContractActivity.this, "请输入订单编号");
            return;
        }

        for (int i = 0; i < beans.size(); i++) {
            if ("1".equals(beans.get(i).getIsSelected())) {
                disCom = beans.get(i).getDisCom();
            }
        }
        if (TextUtils.isEmpty(disCom)) {
            ToastUtils.showToast(ReturnContractActivity.this, "请重新输入快递编号，获取快递公司");
            return;
        }
        disNum = cetCodeInput.getText().toString();
        HttpManager.getInstance().setOrderBackWay(orderId, disCom, disNum).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<RetunContactBean>() {
            @Override
            public void onNext(RetunContactBean o) {
                if ("1".equals(o.getResult())) {
                    ToastUtils.showToast(ReturnContractActivity.this, "回寄成功");
                    finish();
                }
            }
        }, this));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PHOTO_CARMERACODE) {
            if (getPermissionsResult(permissions)) {
                //允许了则扫描
                Intent intent = new Intent();
                intent.setClass(ReturnContractActivity.this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, Config.SCANNIN_GREQUEST_CODE);
            } else {
                ToastUtils.showToast(ReturnContractActivity.this, "请到设置里设置拍照等权限");
            }
        }
    }
    
    /**
     * 判断权限是否都开启了
     */
    public boolean getPermissionsResult(String[] permissions) {
        boolean permessionFlag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(ReturnContractActivity.this, permissions[i])
                    != PackageManager.PERMISSION_GRANTED) {
                permessionFlag = false;
                break;
            } else {
                permessionFlag = true;
                continue;
            }
        }
        return permessionFlag;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //处理二维码扫描结果
            case Config.SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    cetCodeInput.setText(bundle.getString("result"));
                    //显示
//                    mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                }
                break;
        }
    }

    /**
     * 点击回调
     *
     * @param position
     */
    @Override
    public void onClick(int position) {
        disCom = beans.get(position).getDisCom();
        gongsiTv.setText(beans.get(position).getDisName());
        for (int i = 0; i < beans.size(); i++) {
            if (i == position){
                beans.get(i).setIsSelected("1");
            }else{
                beans.get(i).setIsSelected("0");
            }
        }
        mAdapter.addData(beans);
        lvExpressList.setVisibility(View.GONE);
    }

}
